package com.mec.fileTransfer.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.mec.fileTransfer.view.IResourceReceiveProgress;

/**
 * 接收端服务器
 * 其中完成文件接收服务器的建立，并且根据资源服务器指派的发送端数量侦听发送客户端的连接请求
 * 侦听到一个客户端之后，派发文件资源接受线程进行文件的接收！ 
 * @author Lconf
 *
 */
public class ResourceReceiverServer implements Runnable {
	private ServerSocket serverSocket;
	private int port;
	private int senderCount;
	private volatile boolean goon;
	private ThreadPoolExecutor threadPool;
	private ReceiveFileSet reseiveFileSet;
	private IResourceReceiveProgress receiveProgress;
	
	protected ResourceReceiverServer() {
		threadPool = new ThreadPoolExecutor
				(40, 100, 500L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
		goon = false;
	}
	
	protected ResourceReceiverServer(int port, int senderCount, ReceiveFileSet reseiveFileSet,
			IResourceReceiveProgress receiveProgress) {
		this();
		this.port = port;
		this.senderCount = senderCount;
		this.reseiveFileSet = reseiveFileSet;
		this.receiveProgress = receiveProgress;
	}

	protected void setPort(int port) {
		this.port = port;
	}
	
	protected void setSenderCount(int senderCount) {
		this.senderCount = senderCount;
		
		if (receiveProgress != null) {
			receiveProgress.setSenderInfo(senderCount);
		}
	}

	protected void setReseiveFileSet(ReceiveFileSet reseiveFileSet) {
		this.reseiveFileSet = reseiveFileSet;
		
		if (receiveProgress != null) {
			receiveProgress.setSenderPlan(
					reseiveFileSet.getTotalReceiveFiles(), 
					reseiveFileSet.getTotalReceiveBytes());
		}
	}
	
	protected ReceiveFileSet getReseiveFileSet() {
		return reseiveFileSet;
	}

	void startReceiverServer() throws Exception {
		if(port == 0) {
			throw new Exception("请先设置服务器端口！");
		}
		
		serverSocket = new ServerSocket(port);
		goon = true;
		synchronized (ResourceReceiverServer.class) {
			//threadPool.execute(server);
			new Thread(this, "MEC-FileReceiveServer").start();
			ResourceReceiverServer.class.wait();
		}
		
		if (receiveProgress != null) {
			receiveProgress.startShowProgress();
		}
		
	}

	@Override
	public void run() {
		int curSenderCount = 0;
		synchronized (ResourceReceiverServer.class) {
			ResourceReceiverServer.class.notify();
		}
		
		//接收资源服务器线程
//		//根据SenderCount负责侦听客户端连接
		while(curSenderCount < senderCount && goon) {
			try {
				Socket sender = serverSocket.accept();
				if (receiveProgress != null) {
					String senderInfo = sender
							.getInetAddress()
							.getHostName();
					receiveProgress.acceptOneSender(senderInfo);
				}
				System.out.println("侦听到一个客户端的连接请求！");
				new ResourceReceiver(sender, threadPool, this, receiveProgress);
				System.out.println("派发接收线程完毕！");
				curSenderCount++;
			} catch (IOException e) {
				goon = false;
				e.printStackTrace();
			}
		}
		/*
		 * TODO 此处的等待方式有待于优化
		 * 如果还有发送端线程未结束，则此处将一直循环等待，不合理。
		 */
		boolean allFinished = threadPool.getActiveCount() <= 0;
		while(!allFinished) {
			allFinished = threadPool.getActiveCount() <= 0;
		}
		try {
			RamdomAccessFlieBuffer.closeRaf();
		} catch (IOException e) {
			e.printStackTrace();
		}
		threadPool.shutdown();
		
		if (receiveProgress != null) {
			receiveProgress.finishedReceive();
		}
	}

}
